package message.activemq.queue;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import message.activemq.ActiveMQUtil;
import org.apache.activemq.ActiveMQConnectionFactory;

/**
 * 先运行多个消费者，再运行生产者，可以看到消息被多个消费者均分消费了
 */
public class QueueProducer {

    //配置服务地址和端口
    private static final String url = "tcp://127.0.0.1:61616";
    //这次发送的消息名称
    private static final String topicName = "queue_style";

    public static void main(String[] args) throws JMSException {
        //检查activemq服务是否开启
        ActiveMQUtil.checkServer();
        //创建ConnectionFactory并绑定url
        ConnectionFactory factory = new ActiveMQConnectionFactory(url);
        //创建Connection
        Connection connection = factory.createConnection();
        //启动连接
        connection.start();
        //创建Session
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        //使用session创建队列
        Destination destination = session.createQueue(topicName);
        //创建消息生产者
        MessageProducer producer = session.createProducer(destination);

        for (int i = 0; i < 100; i++) {
            //创建消息
            TextMessage textMessage = session.createTextMessage("队列消息=>" + i);
            //发送消息
            producer.send(textMessage);
            System.out.println("发送队列queue消息:" + textMessage.getText());
        }
        //关闭连接
        producer.close();
        session.close();
        connection.close();
    }
}